package com.sdk.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout.LayoutParams;

import com.com.unionpay.utils.DeviceUtils;
import com.sdk.LogUtils;

/**
 * <pre>
 *     author : liuso
 *     e-mail : xxx@xx
 *     time   : 2018/11/29
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class FreeImageView extends android.support.v7.widget.AppCompatImageView {

    private final String TAG = this.getClass().getSimpleName();

    private Context context;//上下文
    private int screenWidth, screenHeight;//屏幕宽高
    public int lastX = -1, lastY = -1;//最后x,y
    private int downX, downY;//按下时x,y
    private int width = -1, height = -1;
    private int statusBarHeight = -1;//状态栏高度
    private boolean isMove;
    private LayoutParams lp;
    private OnListener listener;//监听
    float mWith = 36;
    float mHeight = 36;
    private float defaultHeight = 0;
    private float topRange = 0;

    //--------------------------------------------
    public FreeImageView(Context context) {
        super(context);
        init(context, null);
    }

    public FreeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public FreeImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        this.context = context;
        this.setFocusable(true);
        this.setScaleType(ScaleType.CENTER_INSIDE);
        this.setClickable(true);
        //获取屏幕尺寸信息
        //如果不设置底部高度限制，这限制高度不溢出底部
        defaultHeight = defaultHeight == 0 ? getHeight() : defaultHeight;

        LogUtils.v("defaultHeigh" + getHeight());
        screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        //LogUtil.v("mWith" + mWith + "mHeight" + mHeight);
        lp = new LayoutParams((int) DeviceUtils.dpToPixel(context, mWith), (int) DeviceUtils.dpToPixel(context, mHeight));
        //Log.v(TAG, "screenW:" + screenWidth + "  screenH:" + screenHeight);
        //获取状态栏高度
        if (statusBarHeight == -1) {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
            Log.v(TAG, "statusBarHeight:" + statusBarHeight);
        }
    }

    //-----------------------------------------------
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                this.setFocusableInTouchMode(true);
                this.requestFocus();
                this.requestFocusFromTouch();

                downX = lastX = (int) event.getRawX();
                downY = lastY = (int) event.getRawY();

                isMove = false;
                if (width == -1) {
                    width = this.getWidth();
                    height = this.getHeight();
                    Log.v(TAG, "w:" + width + " h:" + height);
                    lp.width = width;
                    lp.height = height;
                }
                //LogUtil.v("down lastX:" + lastX + "  lastY:" + lastY);
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY;
                if (!isMove) {
                    int dx1 = Math.abs((int) event.getRawX() - downX);
                    int dy1 = Math.abs((int) event.getRawY() - downY);
                    if (dx1 > 20 || dy1 > 20) {
                        isMove = true;
                    }
                }
                if (isMove) {
                    int top = this.getTop() + dy;
                    int left = this.getLeft() + dx;
                    int bottom = this.getBottom() - dy;
                    //不能移动到状态栏和标题栏上
                    if (top < (int) DeviceUtils.dpToPixel(context, topRange)) {
                        top = (int) DeviceUtils.dpToPixel(context, topRange);
                    }
                    //不能移动到购买按钮上
                    if (top > screenHeight - (int) DeviceUtils.dpToPixel(context, defaultHeight)) {
                        top = screenHeight - (int) DeviceUtils.dpToPixel(context, defaultHeight);
                    }
                    //Log.v(TAG, "move x:" + event.getRawX() + " y:" + event.getRawY() + " left:" + left + " top:" + top + " getLeft:" + getLeft() + " getTop:" + getTop());
                    lp.setMargins(left, top, 0, 0);
                    setLayoutParams(lp);
                }
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
//                LogUtil.v("move lastX:" + lastX + "  lastY:" + lastY);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (listener != null && !isMove && !isLongClickable()) {
                    listener.onClick(this);
                }
                int l_x = Math.abs((int) event.getRawX());
                int t_y = Math.abs((int) event.getRawY());
                int r_x = screenWidth - l_x;//距离屏幕右边距
                int b_y = screenHeight - t_y;//距离底部距离
                //x坐标，距离右边距，距离底部距离
                int edgeId = getEdge(l_x, r_x, b_y);

                int top1 = this.getTop();
                int left1 = this.getLeft();
                switch (edgeId) {
                    case 0://靠左
                        left1 = 0;
                        break;
                    case 2://靠右
                        left1 = screenWidth - width;
                        break;
                }
                lp.setMargins(left1, top1, 0, 0);
                setLayoutParams(lp);
                lastX = left1;
                lastY = top1;
                //LogUtil.v("up lastX:" + lastX + "  lastY:" + lastY + " left:" + left1 + " top:" + top1);
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * @param left   距离左边
     * @param right  距离右边距
     * @param bottom 距离底部距离
     * @return 0右边;1底部;2左边
     */
    private int getEdge(int left, int right, int bottom) {
        int edgeId = 0;//默认偏右边
        if (right < left) {//偏左
            edgeId = 2;
        }
        return edgeId;
    }
    //--------------------------------

    /**
     * 设置事件监听
     *
     * @param listener
     */
    public void setOnListener(OnListener listener) {
        this.listener = listener;
    }

    public FreeImageView setWithAndHeight(float with, float height, int defaultHeight) {
        lp = new LayoutParams((int) DeviceUtils.dpToPixel(context, with), (int) DeviceUtils.dpToPixel(context, height));
        return this;
    }

    public FreeImageView setRangeLimitBottom(int bottomLimit) {
        this.defaultHeight = bottomLimit;
        return this;
    }
    public FreeImageView setRangeLimitTop(int topLimit) {
        this.topRange = topLimit;
        return this;
    }

    public FreeImageView setDrawableResouce(int resource) {
        setImageResource(resource);
        return this;
    }

    public FreeImageView setBackground(int resource) {
        setBackgroundResource(resource);
        return this;
    }

    /**
     * 点击监听设置
     */
    public interface OnListener {
        public void onClick(View view);
    }


}
